package cn.oyjg.debugTool;

import cn.oyjg.debugTool.db.SQLiteHelper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.net.URLEncoder;
import java.util.*;

public class About extends JDialog {

	private final JPanel contentPanel = new JPanel();
	private JTextField txt_keyword;
	SQLiteHelper db = new SQLiteHelper();
	App app = null;
	JTextArea textArea ;
	private SQLiteHelper sqlHelp = new SQLiteHelper();
	private String requestURL = sqlHelp.querySetting(1);

	/**
	 * Create the dialog.
	 */
	public About(App app) {
		this.app = app;
		this.setTitle("城市检索");
		setBounds(100, 100, 827, 526);
		getContentPane().setLayout(new BorderLayout());
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		contentPanel.setLayout(new BorderLayout(0, 0));
		
		JScrollPane scrollPane = new JScrollPane();
		contentPanel.add(scrollPane);
		
		textArea = new JTextArea();
		scrollPane.setViewportView(textArea);
		txt_keyword = new JTextField();
		scrollPane.setColumnHeaderView(txt_keyword);
		txt_keyword.setColumns(10);
		txt_keyword.addKeyListener(new KeyListener() {
			@Override
			public void keyTyped(KeyEvent e) {

			}

			@Override
			public void keyPressed(KeyEvent e) {
				
			}

			@Override
			public void keyReleased(KeyEvent e) {
				new Thread(()->{
					bindData();
				}).start();
			}
		});

	}

	private void bindData() {
		String keyword = this.txt_keyword.getText().trim();
		try {
			if(keyword.equals("") || keyword.length()<2){
				return;
			}
			String url = requestURL+"/inp/area/queryCity?json=%7B%22keyword%22%3A%22" + URLEncoder.encode(keyword,"utf-8") + "%22%7D";
			Connection.Response response = Jsoup.connect(url).ignoreContentType(true).timeout(1000 * 60).method(Connection.Method.GET).execute();
			String result = response.body();
			result="{\""+result.substring(result.indexOf("content"),result.length()-5);
			Gson gson = new Gson();
			java.util.List<City> data = gson.fromJson(result, new TypeToken<java.util.List<City>>() {
			}.getType());

			String t="";
			for(City r: data){
				t+=r.b+"\r\n";
			}
			textArea.setText(t);
		} catch (Exception err) {
			err.printStackTrace();
		}
	}
	class City{
		public String a;
		public String b;
	}
}

